<?php

namespace App\controller;

use app\common\MsgType;
use App\model\Equip;
use app\model\Item;
use App\model\Mail;
use App\model\Trade;
use App\model\TradeLog;
use app\model\User;
use GatewayWorker\Lib\Gateway;
use support\Constant;
use support\Db;
use support\Request;
use support\Response;

class TradeController extends CommonController
{
    /**
     * 上架商品
     * @param Request $request
     * @return Response
     */
    public function putOn(Request $request)
    {
        $data = $request->postData;
        // print_r($data);
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;
        $item_key = $data['item_key'] ?? '';
        $attrs = $data['attrs'] ?? '';
        $price = $data['price'] ?? 0;
        $nickname = $data['nickname'] ?? '';//指定玩家
        $on_time = $data['on_time'] ?? 0;//
        $num = $data['num'] ?? 0;//

        $ip = $request->getRealIp();

        if (empty($uuid) || empty($role_id) || empty($item_key) || empty($attrs)) {
            return outJson(1, '参数为空');
        }

        //限制一个ip,一天只能上架5件商品
        $trade_total = Trade::query()->where('uuid', $uuid)->whereBetween('created_at', getTodayStartEndTimestamp())->where('is_off', 0)->count();
        if ($trade_total >= 5) {
            return outJson(1, '本日上架商品超过限制！');
        }

        // return outJson(1, '暂时不能上架！');

        $cate = Constant::TRADE_ITEM_CATE_5;
        $item_name = '';
        if (isItem($item_key)) {
            $item_info = Item::getItemByItemKey($item_key);
            $item_name = $item_info['物品名称'];
            if ($item_info['道具类型'] == 5) {
                $cate = Constant::TRADE_ITEM_CATE_4;
            }
        } else {
            $item_info = Equip::getItemByItemKey($item_key);
            $item_name = $item_info['装备名称'];
            if ($item_info['装备部位'] == 1) {
                $cate = Constant::TRADE_ITEM_CATE_1;
            } elseif (in_array($item_info['装备部位'], [2, 3, 5, 8, 9])) {
                $cate = Constant::TRADE_ITEM_CATE_2;
            } elseif (in_array($item_info['装备部位'], [4, 6, 7])) {
                $cate = Constant::TRADE_ITEM_CATE_3;
            }
        }

        //判断物品是否存在
        if (empty($item_info)) {
            return outJson(1, '物品不存在');
        }

        //获取玩家的uuid
        $special_uuid = User::query()->where('nickname', $nickname)->value('uuid');
        $trade_model = new Trade();
        $trade_model->uuid = $uuid;
        $trade_model->role_id = $role_id;
        $trade_model->item_key = $item_key;
        $trade_model->item_name = $item_name;
        $trade_model->attrs = $attrs;
        $trade_model->price = $price;
        $trade_model->special_nickname = $nickname;
        $trade_model->special_uuid = intval($special_uuid);
        $trade_model->price = $price;
        $trade_model->on_time = $on_time;
        $trade_model->num = $num;
        $trade_model->cate = $cate;
        $trade_model->ip = $request->getRealIp();
        $trade_model->save();
        return outJson(0, '创建成功！');
    }

    /**
     * 商品列表
     * @param Request $request
     * @return Response
     */
    public function itemList(Request $request)
    {
        $data = $request->postData;
        $cate = $data['cate'] ?? 0;
        $keyword = $data['keyword'] ?? '';
        $page = $data['page'] ?? 1;
        $per_page = $data['per_page'] ?? 10;
        $order_by = $data['order_by'] ?? Constant::TRADE_ITEM_ORDER_BY_1;

        $cond_where = [];
        $cond_where['is_off'] = 0;
        if ($cate) {
            $cond_where['cate'] = $cate;
        }
        if ($keyword) {
            $cond_where[] = [function ($query) use ($keyword) {
                $query->where('item_name', 'like', '%' . $keyword . '%');
            }];
        }

        $order_by_cond = [];
        if ($order_by == Constant::TRADE_ITEM_ORDER_BY_1) {
            $order_by_cond['created_at'] = 'desc';
        } elseif ($order_by == Constant::TRADE_ITEM_ORDER_BY_2) {
            $order_by_cond['created_at'] = 'asc';
        } elseif ($order_by == Constant::TRADE_ITEM_ORDER_BY_3) {
            $order_by_cond['price'] = 'desc';
        } elseif ($order_by == Constant::TRADE_ITEM_ORDER_BY_4) {
            $order_by_cond['price'] = 'asc';
        } elseif ($order_by == Constant::TRADE_ITEM_ORDER_BY_5) {
            $order_by_cond['num'] = 'desc';
        } elseif ($order_by == Constant::TRADE_ITEM_ORDER_BY_6) {
            $order_by_cond['num'] = 'asc';
        }

        $count = Trade::query()->where($cond_where)->count();
        $lists = Trade::query()->where($cond_where)->orderBy(key($order_by_cond), current($order_by_cond))->paginate($per_page, '*', 'page', $page)->items();

        $_list = [];
        foreach ($lists as $item) {
            $_list[] = [
                'id' => $item['id'],
                'item_key' => $item['item_key'],
                'item_name' => $item['item_name'],
                'num' => $item['num'],
                'price' => $item['price'],
                'attrs' => $item['attrs'] ?: [],
            ];
        }

        print_r($_list);

        $out_data['list'] = $_list;
        // $out_data['list'] = [];
        $out_data['total_num'] = $count;
        $out_data['page'] = $page;
        $out_data['per_page'] = $per_page;
        return outJson(0, 'ok', $out_data);
    }

    /**
     * 购买商品
     * @param Request $request
     * @return Response
     */
    public function buy(Request $request)
    {
        $data = $request->postData;
        print_r($data);
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;
        $trade_id = $data['trade_id'] ?? 0;
        if (empty($uuid) || empty($role_id) || empty($trade_id)) {
            return outJson(1, '参数为空');
        }

        // return outJson(1, '暂时不能购买！');

        //判断是否过期
        $trade_info = Trade::query()->where('id', $trade_id)->first();
        if (empty($trade_info)) {
            return outJson(1, '交易不存在');
        }
        if ($trade_info['is_off'] == 1) {
            return outJson(1, '商品已下架');
        }
        // $trade_info = $trade_info->toArray();
        // print_r($trade_info['attrs']);

        $expire_time = strtotime($trade_info['created_at']) + $trade_info['on_time'] * 86400;
        if (time() > $expire_time) {
            return outJson(1, '已过期');
        }

        //判断是不是指定玩家才可以购买
        if ($trade_info['special_uuid'] and $uuid != $trade_info['special_uuid']) {
            return outJson(1, '指定玩家才购买！');
        }

        $trade_info->is_off = 1;
        $trade_info->save();

        //记录交易日志
        TradeLog::create(
            [
                'trade_id' => $trade_id,
                'buy_uuid' => $uuid,
                'buy_role_id' => $role_id,
                'ip' => $request->getRealIp(),
            ]
        );

        //发送邮件给购买者
        $mail_model = new Mail();
        $mail_model->type = Constant::MAIL_TYPE_2;
        $mail_model->uuid = $uuid;
        $mail_model->role_id = $role_id;
        $mail_model->title = '交易行购买物品';
        $mail_model->content = sprintf("#a59a83您在交易行购买了物品#ffaa3b【%s】,请及时领取附件", $trade_info['item_name']);
        $attach_items = [];
        $attach_items[] = ['item_key' => $trade_info['item_key'], 'num' => $trade_info['num'], 'attrs' =>
            $trade_info['attrs']];
        $mail_model->attach = $attach_items;
        $mail_model->save();

        $real_uuid = $uuid . '-' . $role_id;
        Gateway::sendToUid($real_uuid, json_encode([
            'type' => MsgType::TYPE_33,
            'email' => 1,
        ]));

        //发送邮件给出售者
        $mail_model = new Mail();
        $mail_model->type = Constant::MAIL_TYPE_3;
        $mail_model->uuid = $trade_info['uuid'];
        $mail_model->role_id = $trade_info['role_id'];
        $mail_model->title = '交易行物品售出';
        $mail_content = "#a59a83交易行卖出了物品《%s》*%s\n售卖银两：%s\n获得银两：%s(%s手续费)\n请及时领取附件！";
        $get_price = round($trade_info['price'] * (1 - Constant::SERVICE_CHARGE / 100));
        $mail_model->content = sprintf($mail_content, $trade_info['item_name'], $trade_info['num'], $trade_info['price'], $get_price, Constant::SERVICE_CHARGE . '%');
        $attach_items = [];
        $attach_items[] = ['item_key' => 100000372, 'num' => $get_price, 'attrs' => []];
        $mail_model->attach = $attach_items;
        $mail_model->save();

        $real_uuid = $trade_info['uuid'] . '-' . $trade_info['role_id'];
        Gateway::sendToUid($real_uuid, json_encode([
            'type' => MsgType::TYPE_33,
            'email' => 1,
        ]));

        return outJson(0, '购买成功，请到邮件领取附件');
    }

    /**
     * 下架
     * @param Request $request
     * @return Response
     */
    public function offShelf(Request $request)
    {
        $data = $request->postData;
        // print_r($data);
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;
        $trade_id = $data['trade_id'] ?? 0;
        if (empty($uuid) || empty($role_id) || empty($trade_id)) {
            return outJson(1, '参数为空');
        }

        $trade_info = Trade::query()->where('id', $trade_id)->first();
        if (empty($trade_info)) {
            return outJson(1, '交易不存在');
        }

        $expire_time = strtotime($trade_info['created_at']) + $trade_info['on_time'] * 86400;
        if (time() > $expire_time) {
            return outJson(1, '已过期');
        }

        //判断是不是自己上架的物品
        if ($trade_info['uuid'] != $uuid) {
            return outJson(1, '不能下架别人的物品');
        }

        //是否下架
        if ($trade_info['is_off'] == 1) {
            return outJson(1, '操作错误 ');
        }

        //记录交易日志
        $trade_info->is_off = 1;
        $trade_info->save();

        //发送邮件给出售者
        $mail_model = new Mail();
        $mail_model->type = Constant::MAIL_TYPE_4;
        $mail_model->uuid = $trade_info['uuid'];
        $mail_model->role_id = $trade_info['role_id'];
        $mail_model->title = '交易行物品下架';
        $mail_model->content = sprintf("#a59a83物品%s已下架，请及时领取附件", $trade_info['item_name']);
        $attach_items = [];
        $attach_items[] = ['item_key' => $trade_info['item_key'], 'num' => $trade_info['num'], 'attrs' =>
            $trade_info['attrs']];
        $mail_model->attach = $attach_items;
        $mail_model->save();


        $real_uuid = $trade_info['uuid'] . '-' . $trade_info['role_id'];
        Gateway::sendToUid($real_uuid, json_encode([
            'type' => MsgType::TYPE_33,
            'email' => 1,
        ]));

        var_dump($real_uuid, json_encode([
            'type' => MsgType::TYPE_33,
            'email' => 1,
        ]));

        return outJson(0, '下架成功，请到邮件领取附件');
    }

    /**
     * 我的上架记录
     * @param Request $request
     * @return Response
     */
    public function myRecord(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'] ?? 0;
        $role_id = $data['role_id'] ?? '';

        $cond_where = [];
        $cond_where['uuid'] = $uuid;
        $cond_where['role_id'] = $role_id;
        $cond_where['is_off'] = 0;
        $lists = Trade::query()->where($cond_where)
            ->orderBy('id', 'desc')->get();
        $lists = $lists ? $lists->toArray() : [];

        $_list = [];
        foreach ($lists as $item) {
            $_list[] = [
                'id' => $item['id'],
                'item_key' => $item['item_key'],
                'item_name' => $item['item_name'],
                'num' => $item['num'],
                'price' => $item['price'],
                'attrs' => $item['attrs'] ?: [],
            ];
        }

        $out_data['list'] = $_list;
        return outJson(0, 'ok', $out_data);
    }

    /**
     * 交易记录
     * @param Request $request
     * @return Response
     */
    public function log(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'] ?? 0;
        $role_id = $data['role_id'] ?? '';
        $page = $data['page'] ?? 1;
        $per_page = $data['per_page'] ?? 10;

        $cond_where = [];
        $count = TradeLog::query()->where($cond_where)->count();
        $lists = TradeLog::query()->where($cond_where)->orderBy('id', 'desc')->paginate($per_page, '*', 'page', $page)->items();
        $trade_ids = array_column($lists, 'trade_id');
        $buy_uuids = array_column($lists, 'buy_uuid');
        $buy_users = User::query()->whereIn('uuid', $buy_uuids)->pluck('nickname', 'uuid')->toArray();

        $trade = Trade::query()->select('trade.*', 'user.nickname')->join('user', 'user.uuid', '=', 'trade.uuid')->whereIn('trade.id', $trade_ids)->get();
        $trade = $trade ? $trade->toArray() : [];

        $trade = array_column($trade, null, 'id');

        // print_r($trade);

        $colors = [
            1 => '#d6d5d5', //白色品质
            2 => '#5eba32', //绿色品质
            3 => '#2e90c5', //蓝色品质
            4 => '#ae4db2', //紫色品质
            5 => '#e59835', //橙色品质
            6 => '#e00202', //红色品质
        ];


        $_list = [];
        foreach ($lists as $list) {
            // #1f981c
            $item_key = $trade[$list['trade_id']]['item_key'];
            $item_info = [];
            if (isItem($item_key)) {
                $item_info = Item::getItemByItemKey($item_key);
            } else {
                $item_info = Equip::getItemByItemKey($item_key);
            }
            $quality = $item_info['品质'] ?? 1;

            $_list[] = sprintf('#a59a83%s,#b6a77a%s#a59a83花费#b76b28%s银两#a59a83购买了#b6a77a%s#a59a83的，%s*%s',
                $list['created_at'],
                $buy_users[$list['buy_uuid']],
                $trade[$list['trade_id']]['price'],
                $trade[$list['trade_id']]['nickname'],
                // $trade[$list['trade_id']]['item_name'],
                $colors[$quality] . $trade[$list['trade_id']]['item_name'],
                $trade[$list['trade_id']]['num']
            );
        }

        $out_data['list'] = $_list;
        $out_data['total_num'] = $count;
        $out_data['page'] = $page;
        $out_data['per_page'] = $per_page;
        return outJson(0, 'ok', $out_data);
    }

}
